from decimal import Decimal
from django_redis import get_redis_connection
# from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from  rest_framework.permissions import IsAuthenticated

from goods.models import SKU
from order.serializer import OrderSerializer, PlaceSerializer


class PlaceOrderAPIView(APIView):


    permission_classes = [IsAuthenticated]

    # def get(self,request):
    #
    #     user = request.user
    #
    #     redis_conn = get_redis_connection('cart')
    #     sku_id_counts = redis_conn.hgetall('cart_%s'%user.id)
    #
    #     redis_cart = {}
    #
    #     for sku_id,count in sku_id_counts.items():
    #         redis_cart[int(sku_id)] = int(count)
    #
    #     selected_ids = redis_conn.smembers('cart_selected_%s'%user.id)
    #
    #     skus = SKU.objects.filter(pk__in=selected_ids)
    #     for sku in skus:
    #         sku.count = redis_cart[sku.id]
    #     # serializer = PlaceOrderSerializer(skus,many=True)
    #     freight = Decimal('10')
    #
    #     serializer = PlaceSerializer({
    #         'skus':skus,
    #         'freight':freight
    #     })
    #
    #     return Response(serializer.data)
    def get(self,request):

        user = request.user

        redis_conn = get_redis_connection('cart')
        sku_id_counts = redis_conn.hgetall('cart_%s'%user.id)

        redis_cart = {}
        for sku_id,count in sku_id_counts.items():
            redis_cart[int(sku_id)]=int(count)

        selected_ids = redis_conn.smembers('cart_selected_%s'%user.id)

        skus =SKU.objects.filter(pk__in=selected_ids)

        for sku in skus:
            sku.count = redis_cart[sku.id]
        freight = Decimal('10')
        serializer = PlaceSerializer({
            'skus':skus,
            'freight':freight
        })

        return Response(serializer.data)


class OrderView(APIView):

    permission_classes = [IsAuthenticated]

    def post(self,request):

        data = request.data
        serializer = OrderSerializer(data=data,context={'request':request})

        serializer.is_valid(raise_exception=True)

        serializer.save()

        return Response(serializer.data)










